import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:orginone/components/CommandWidget/index.dart';
import 'package:orginone/dart/base/storages/storage.dart';
import 'package:orginone/pages/home/components/BadgeTabWidget/BadgeTabWidget.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/KeepAliveWidget/KeepAliveWidget.dart';
import 'package:orginone/components/ExpandTabBar/ExpandTabBar.dart';
import 'package:orginone/components/XStatefulWidget/XStatefulWidget.dart';
import 'package:orginone/components/Tip/QuitAppTipWidget.dart';
import 'package:orginone/components/AppUpdate/AppUpdate.dart';
import 'package:orginone/dart/base/common/commands.dart';
import 'package:orginone/dart/controller/index.dart';
import 'package:orginone/dart/core/target/base/belong.dart';
import 'package:orginone/main.dart';
import 'package:orginone/pages/chats/chat_page.dart';
import 'package:orginone/components/MySettingWidget/MySettingWidget.dart';
import 'package:orginone/pages/portal/assets_management/assets_module/asset_select_modal.dart';
import 'package:orginone/pages/portal/portal_page.dart';
import 'package:orginone/pages/relation/relation_page.dart';
import 'package:orginone/pages/store/store_page.dart';
import 'package:orginone/pages/work/work_page.dart';
import 'package:orginone/routers/app_route.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/routers/router_const.dart';
import 'package:orginone/utils/log/log_util.dart';
import 'package:provider/provider.dart';
import '../../dart/core/target/team/company.dart';
import '../../utils/system/system_utils.dart';

/// 首页
class HomePage extends XStatefulWidget {
  bool isHomePage;
  late Map<HomeEnum, AppRoute> _routeDataMap;

  HomePage({super.key, this.isHomePage = true, super.data}) {
    loadSpace();
  }

  void loadSpace() {
    super.routeData = RoutePages.routeData;
    _routeDataMap = {};
    var doorRouteData = AppRoute();
    _routeDataMap[HomeEnum.door] = doorRouteData;
    IBelong? currentSpace = relationCtrl.user?.currentSpace;

    if (null != currentSpace) {
      List<IBelong>? belongList = relationCtrl.user?.belongList;
      doorRouteData.currPageData.title = currentSpace.name;
      doorRouteData.currPageData.entity = currentSpace;
      doorRouteData.currPageData.entitys = belongList;
      if (relationCtrl.homeEnum.value == HomeEnum.door) {
        super.routeData?.currPageData.title = currentSpace.name;
        super.routeData?.currPageData.entity = currentSpace;
        super.routeData?.currPageData.entitys = belongList;
        super.routeData?.currPageData.data = HomeEnum.door;
      }
    }
    super.routeData?.currPageData.path = Routers.home;
  }

  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends XStatefulState<HomePage, dynamic> {
  var currentIndex = 0.obs;
  HomeEnum get homeEnum => relationCtrl.homeEnum.value;
  var data;

  @override
  void initState() {
    super.initState();
    // 获取设备序列号
    SystemUtils.getDeviceIdSync();
    AppUpdate.instance.update();
    Storage.setBool('switchflag', true);
    relationCtrl.data.home!.switchSpace(relationCtrl.data.home!.selectSpace);
    Future.wait(
        relationCtrl.user!.companys.map((e) => e.loadMembers(reload: true)));
    getCurrentCompany()?.standard.directory.loadDirectoryResource(reload: true);
    relationCtrl.user?.updateCurrentSpace(relationCtrl.data.home!.selectSpace);
  }

  /// 获得当前单位
  ICompany? getCurrentCompany({String? companyId}) {
    return null != relationCtrl.user
        ? relationCtrl.user!.findCompany(
        companyId ?? RoutePages.routeData.currPageData.entity?.id ?? "")
        : null;
  }

  @override
  Widget buildWidget(BuildContext context, dynamic data) {
    // LogUtil.d(">>>>>>>=======home");
    return QuitAppTipWidget(
        child: DefaultTabController(
            length: 5,
            initialIndex: _getTabCurrentIndex(),
            animationDuration: Duration.zero,
            child: Column(
              children: [
                Expanded(
                  child: Column(
                    children: [
                      Expanded(
                        child: ExtendedTabBarView(
                          // shouldIgnorePointerWhenScrolling: false,
                          children: [
                            KeepAliveWidget(child: ChatPage()),
                            KeepAliveWidget(child: WorkPage()),
                            const PortalPage(),
                            const StorePage(),
                            const RelationPage(),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                // InfoListPage(relationCtrl.relationModel),
                // bottomButton(),
                _HomeBottomBar(widget._routeDataMap, isHomePage(context))
              ],
            )));
  }

  int _getTabCurrentIndex() {
    return HomeEnum.values
        .indexWhere((element) => element == relationCtrl.homeEnum.value);
  }

  @override
  void Function()? onTapTitle(BuildContext context) {
    AppRoute? rd = widget._routeDataMap[homeEnum];
    if (homeEnum == HomeEnum.door) {
      Storage.setBool('switchflag', true);
      showSearchApplication(context, rd?.currPageData.entitys ?? [],
          title: "切换单位", hint: "搜索", onSelected: (selectData) async {
        command.emitterFlag('switchSpace', /*[rd]*/selectData[0]);
        context.read<AppRoute>().setData(
            title: selectData[0].name,
            entity: selectData[0],
            entitys: rd?.currPageData.entitys);
        relationCtrl.data.home!.switchSpace(selectData[0]);
        relationCtrl.user?.updateCurrentSpace(selectData[0]);
      });
    } else if (RoutePages.isHomePage()) {
      super.openDrawer(context);
    }
    return null;
  }

  @override
  List<Widget>? buildButtons(BuildContext context, dynamic data) {
    List<Widget> res = [
      // SizedBox(
      //     width: 50,
      //     child: CommandWidget<List<dynamic>>(
      //         type: 'connection',
      //         cmd: 'state',
      //         builder: (context, args) {
      //           args ??= [kernel.isOnline, kernel.online];
      //           return GestureDetector(
      //             onTap: () async {
      //               var res = false;
      //               if (kernel.isOnline) {
      //                 res = await kernel.tokenAuth();
      //               } else {
      //                 res = await kernel.checkOnline();
      //               }
      //               ToastUtils.showMsg(msg: "重连${kernel.online},$res!");
      //             },
      //             child: Text("${args[1]}",
      //                 style: TextStyle(
      //                     fontSize: 16,
      //                     color: args[0] ? Colors.blue : Colors.red)),
      //           );
      //         })),
    ];
    if (relationCtrl.homeEnum == HomeEnum.work) {
      res.addAll(XImage.operationIcons([
        XImage.search,
        XImage.scan,
        // XImage.startWork,
      ]));
    } else if (relationCtrl.homeEnum == HomeEnum.store) {
      res.addAll(XImage.operationIcons([
        XImage.search,
        // XImage.addStorage,
      ]));
    } else if (relationCtrl.homeEnum == HomeEnum.relation) {
      res.addAll(XImage.operationIcons([
        XImage.search,
        // XImage.joinGroup,
      ]));
    } else if (relationCtrl.homeEnum == HomeEnum.door) {
      res.addAll(XImage.operationIcons([
        // XImage.search,
        XImage.scan,
        // XImage.portalNav,
      ]));
    } else {
      res.addAll(XImage.operationIcons([
        XImage.search,
        XImage.scan,
        XImage.add,
      ]));
    }
    return res;
  }

  @override
  Widget buildDrawer(BuildContext context) {
    return const MySettingWidget();
  }
}

class _HomeBottomBar extends StatefulWidget {
  final bool isHomePage;
  Map<HomeEnum, AppRoute> routeDataMap;
  _HomeBottomBar(this.routeDataMap, this.isHomePage);

  @override
  State<StatefulWidget> createState() => __HomeBottomBarState();
}

class __HomeBottomBarState extends State<_HomeBottomBar> {
  Map<HomeEnum, AppRoute> get routeDataMap => widget.routeDataMap;
  TabController? _tabController;
  // late String _switchHomeKey;

  @override
  void initState() {
    super.initState();
    // _switchHomeKey = command.subscribeByFlag('switchHome', ([args]) {
    //   _tabController
    //       ?.animateTo(HomeEnum.values.indexOf(relationCtrl.homeEnum.value));
    // });
  }

  @override
  void dispose() {
    super.dispose();
    // command.unsubscribeByFlag(_switchHomeKey);
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AppRoute>(
      builder: (context, data, childs) {
        return bottomButton(context);
      },
    );
  }

  Widget bottomButton(BuildContext context) {
    _tabController = DefaultTabController.of(context);
    return Container(
      padding: EdgeInsets.only(top: 18.h, bottom: 5.h),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(color: Colors.grey.shade400, width: 0.4),
        ),
      ),
      child: ExpandTabBar(
        controller: _tabController,
        tabs: [
          ExtendedTab(
              child: CommandWidget(
                  type: 'chat',
                  cmd: 'new',
                  builder: (context, args) => button(
                      homeEnum: HomeEnum.chat,
                      path: 'chat',
                      badge: relationCtrl
                          .provider.chatProvider?.noReadChatCount))),
          ExtendedTab(
              child: CommandWidget(
                  flag: 'todo',
                  builder: (context, args) => button(
                      homeEnum: HomeEnum.work,
                      path: 'work',
                      badge: relationCtrl.provider.work?.todos.length))),
          ExtendedTab(child: button(homeEnum: HomeEnum.door, path: 'home')),
          ExtendedTab(child: button(homeEnum: HomeEnum.store, path: 'store')),
          ExtendedTab(
            child: button(homeEnum: HomeEnum.relation, path: 'relation'),
          ),
        ],
        onTap: (index) {
          XLogUtil.d(">>>>====ModelTabs.onTap");
          jumpTab(context, HomeEnum.values[index]);
        },
        indicator: const BoxDecoration(),
      ),
    );
  }

  Widget button(
      {required HomeEnum homeEnum, required String path, int? badge}) {
    ThemeData td = Theme.of(context);
    var isSelected = relationCtrl.homeEnum == homeEnum;
    // var mgsCount = 0;
    // if (homeEnum == HomeEnum.work) {
    //   mgsCount = relationCtrl.provider.work?.todos.length ?? 0;
    // } else if (homeEnum == HomeEnum.chat) {
    //   mgsCount = relationCtrl.provider.chatProvider?.noReadChatCount ?? 0;
    // }
    return BadgeTabWidget(
      imgPath: path,
      foreColor: isSelected ? td.primaryColor : td.unselectedWidgetColor,
      body: Text(homeEnum.label),
      mgsCount: badge ?? 0,
    );
  }

  void jumpTab(BuildContext context, HomeEnum relation) {
    relationCtrl.homeEnum.value = relation;
    AppRoute rd = context.read<AppRoute>();
    AppRoute? newRD = routeDataMap[relation];
    if (null != newRD) {
      rd.setData(
          title: newRD.currPageData.title,
          entity: newRD.currPageData.entity,
          entitys: newRD.currPageData.entitys);
    } else {
      if (rd.hasMore) {
        routeDataMap[HomeEnum.door]?.currPageData.title = rd.currPageData.title;
        routeDataMap[HomeEnum.door]?.currPageData.entity =
            rd.currPageData.entity;
      }
      rd.setData(title: relation.label, entity: relationCtrl.user);
    }
    // _tabController
    //     ?.animateTo(HomeEnum.values.indexOf(relationCtrl.homeEnum.value));
  }
}
